from pymysql import *
from flask import current_app
from pymysql.cursors import DictCursor

class Connection():
    # 初始化对象，提供连接数据库的参数
    def __init__(self, host='', user='', password='', database='',  port=3306,charset='utf8'):
        self.host = host
        self.port = port
        self.database = database
        self.user = user
        self.password = password
        self.charset = charset
        self.open()
    # 建立连接并获得cursor对象
    def open(self):
        print("连接数据库")
        self.conn = connect(host=self.host, port=self.port, db=self.database, user=self.user,
                              passwd=self.password, charset=self.charset)
        self.cursor = self.conn.cursor(DictCursor)

    # 关闭conn对象
    def close(self):
        self.cursor.close()
        self.conn.close()

    # 查询所有未删除的数据
    def selectall(self, sql):
        try:
            # 构造select语句
            self.cursor.execute(sql)
            self.conn.commit()
            result = self.cursor.fetchall()
            # 判断结果并返回
            if result:
                return result
            else:
                return None
        except Exception as e:
            print(sql)
            self.conn.rollback()
            current_app.logger.error('查询失败%s' % (e))


    def selectone(self, sql):
        try:
            # 构造select语句
            self.cursor.execute(sql)
            self.conn.commit()
            result = self.cursor.fetchone()

            # 判断结果并返回
            if result:
                return result
            else:
                return None
        except Exception as e:
            print(sql)
            self.conn.rollback()
            current_app.logger.error('查询失败%s' % (e))


    # 执行insert语句的方法
    def execute(self, sql):
        try:
            # 构造insert语句
            result = self.cursor.execute(sql)
            self.conn.commit()
            # 判断是否成功
            if result == 1:
                return True
            else:
                return False
        except Exception as e:
            print(sql)
            current_app.logger.error('插入失败%s' % (e))
            self.conn.rollback()
            return False


